/*
 * @Author: lvgrape lvgrape@outlook.com
 * @Date: 2024-05-13 16:35:21
 * @LastEditors: lvgrape lvgrape@outlook.com
 * @LastEditTime: 2024-05-15 10:22:18
 * @FilePath: \ZINO_RC_RT\ZINO\hardware\rgb\battery_led.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <rtthread.h>
#include <rtdevice.h>
#include "zino.h"
#include "rgb.h"

#define DBG_TAG "battery_led"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define pwm_dev_name "pwm3"
struct rt_device_pwm *led_dev;

int battery_led_init(void)
{
    led_dev = (struct rt_device_pwm *)rt_device_find(pwm_dev_name);
    if (led_dev == RT_NULL)
    {
        LOG_E("Can't find %s device!", pwm_dev_name);
        return -RT_ERROR;
    }
    rt_pwm_set(led_dev, 1, 10240, 10240);
    rt_pwm_set(led_dev, 2, 10240, 10240);
    rt_pwm_set(led_dev, 3, 10240, 10240);
    rt_pwm_set(led_dev, 4, 10240, 10240);

    rt_pwm_enable(led_dev, 1);
    rt_pwm_enable(led_dev, 2);
    rt_pwm_enable(led_dev, 3);
    rt_pwm_enable(led_dev, 4);

    LOG_I("battery_led init success!");
    return RT_EOK;
}
uint8_t breath=0;
uint16_t breath_cnt=0;
uint16_t level_cnt=0;
void battery_led_set(uint8_t level, uint8_t Charging)
{
    if (!Charging)
    {
        breath_cnt++;
        rt_pwm_set(led_dev, 1, 10000, 10000);
        rt_pwm_set(led_dev, 2, 10000, 10000);
        rt_pwm_set(led_dev, 3, 10000, 10000);
        rt_pwm_set(led_dev, 4, 10000, 10000);
        if(breath_cnt<200)
        {
            breath = breath_cnt;
        }
        else
        {
            breath = 400-breath_cnt;
        }

        if(breath_cnt>=400)
        {            
            breath_cnt=0;
        }
        for(uint8_t i=0;i<level;i++)
        {
            rt_pwm_set(led_dev, i+1, 10000, 10000-breath*25);
        }
    }
    else
    {
        
        breath_cnt++;        
        if(breath_cnt<100)
        {
            breath = breath_cnt;
        }
        rt_pwm_set(led_dev, level_cnt+1, 10000, 10000-breath*100);
        if(breath_cnt>=100)
        {            
            breath_cnt=0;
            level_cnt++;
        }
        if(level_cnt >= level)
        {
            level_cnt = 0;
            rt_pwm_set(led_dev, 1, 10000, 10000);
            rt_pwm_set(led_dev, 2, 10000, 10000);
            rt_pwm_set(led_dev, 3, 10000, 10000);
            rt_pwm_set(led_dev, 4, 10000, 10000);
        }
    }
    // LOG_D("level_cnt:%d/%d",level_cnt,breath);
    rt_pwm_enable(led_dev, 1);
    rt_pwm_enable(led_dev, 2);
    rt_pwm_enable(led_dev, 3);
    rt_pwm_enable(led_dev, 4);
}

ZINO_APP_EXPORT(battery_led_init);